<template>
  <div id="quotation">
    <div class="nav">
      <span :class="[active==0?'active':'']" @click="tab(0)">CNN</span>
      <!--<span :class="[active==1?'active':'']" @click="tab(1)">USDT</span>-->
      <!--<span :class="[active==2?'active':'']" @click="tab(2)">BTC</span>-->
      <!--<span :class="[active==3?'active':'']" @click="tab(3)">ETH</span>-->
    </div>
    <div class="rootMain">
      <Scroll :on-refresh="onRefresh" :on-infinite="onInfinite">
        <div class="scroll-box">
          <div :class="['top', $store.state.scrollTop > 0 ?'fixedHeader':'']">
            <div class="main">
              <div class="list">
                <div class="list-item" @click="goQuotionInfo(active)">
                  <div class="left">
                    <h4>
                      VC
                      <label>/ CNN</label>
                    </h4>
                    <p>24H量 {{volumn}}</p>
                  </div>
                  <div class="center">
                    <h4>{{newprice}}</h4>
                    <p>￥{{newprice}}</p>
                  </div>
                  <div class="right">
                    <div :class="['btn',ratio>0? 'bg-up':'bg-down']">{{ratio}}%</div>
                  </div>
                </div>
                <!--<div
                  class="list-item"
                  @click="goQuotionInfo(e.index)"
                  v-for="(e,i) in coinListHuobi"
                  :key="i"
                >
                  <div class="left">
                    <h4>
                      {{e.coin}}
                      <label>/ {{e.name}}</label>
                    </h4>
                    <p>24H量 {{e.vol | toFixed0}}</p>
                  </div>
                  <div class="center">
                    <h4>{{e.newprice1}}</h4>
                    <p>￥{{e.newprice1}}</p>
                  </div>
                  <div class="right">
                    <div :class="['btn',e.ratio>0? 'bg-up':'bg-down']">{{e.ratio}}%</div>
                  </div>
                </div>-->

              </div>
            </div>
          </div>
        </div>
      </Scroll>
    </div>
    <Footer></Footer>
  </div>
</template>
<script>
import Services from "@/service/index.js";
import { mapMutations, mapState } from "vuex";
import Header from "@/components/header";
import Footer from "@/components/footer";
import Scroll from "@/components/scroll";
import axios from "axios";
import { Dialog, Toast, Popup } from "vant";
import pako from "pako";

export default {
  data() {
    return {
      loginToken: "",
      userObj: {},
      show: false,
      titleStyle: {
        background: "#f10"
      },
      coinList: [
        {
          index: 0,
          name: "CNN",
          coin: "CNN"
        }
      ],
      coinListHuobi: [
        {
          index: 1,
          name: "CNN",
          coin: "BTC",
          newprice: 0,
          newprice1: 0,
          ratio: 0,
          vol: 0
        },
        {
          index: 2,
          name: "CNN",
          coin: "ETH",
          newprice: 0,
          newprice1: 0,
          ratio: 0,
          vol: 0
        },
        {
          index: 3,
          name: "CNN",
          coin: "EOS",
          newprice: 0,
          newprice1: 0,
          ratio: 0,
          vol: 0
        }
      ],
      newprice: "",
      ratio: "",
      timer: null,
      volumn: "",
      active: 0,
      data: "",
      // ratio2: "",
      websock: null,
      usdtCny: ""
    };
  },
  created() {
    this.getConfig();
    this.changeTitle("FUZE");
    this.changetabbarIndex(3);
    this.loginToken = localStorage.getItem("token")
      ? localStorage.getItem("token")
      : "";
    this.userObj = localStorage.getItem("userObj")
      ? JSON.parse(localStorage.getItem("userObj"))
      : "";
    this.getnewPrice();
    this.timer = setInterval(() => {
      // if (this.active == 0) {
      this.getnewPrice();
      // } else {
      //   this.huobiGet24HTrade(this.active);
      // }
    }, 6000);
  },
  components: {
    Scroll,
    Header,
    Footer
  },
  filters: {
    toFixed0(value) {
      let realVal = "";
      if (!isNaN(value) && value !== "") {
        // 截取当前数据到小数点后*位
        realVal = parseFloat(value).toFixed(0);
      } else {
        realVal = "--";
      }
      return realVal;
    },
    toFixed3(value) {
      let realVal = "";
      if (!isNaN(value) && value !== "") {
        // 截取当前数据到小数点后*位
        realVal = parseFloat(value).toFixed(3);
      } else {
        realVal = "--";
      }
      return realVal;
    }
  },
  computed: {
    ...mapState({})
  },
  methods: {
    ...mapMutations(["changeTitle", "changetabbarIndex"]),
    getConfig() {
      Services.getConfig().then(res => {
        if (res.code == "0000") {
          this.usdtCny = res.usdtCny;
          // this.initWebSocket();
        } else {
          Toast(res.msg);
        }
      });
    },
    // 使用websocket请求火币平台数据
    initWebSocket() {
      //初始化weosocket
      const wsuri = "wss://api.huobiasia.vip/ws";
      this.websock = new WebSocket(wsuri);
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onclose = this.websocketclose;
    },
    websocketonopen() {
      //连接建立之后执行send方法发送数据
      let from = { sub: "market.btcusdt.detail" };
      let from1 = { sub: "market.ethusdt.detail" };
      let from2 = { sub: "market.eosusdt.detail" };

      // this.websocketsend(JSON.stringify(from));
      // this.websocketsend(JSON.stringify(from1));
      // this.websocketsend(JSON.stringify(from2));
    },
    websocketonerror() {
      //连接建立失败重连
      // this.initWebSocket();
    },
    websocketonmessage(evt) {
      //数据接收
      let _that = this;
      if (evt.data instanceof Blob) {
        let result = "";
        let reader = new FileReader();
        //FileReader：从Blob对象中读取数据
        reader.onload = function() {
          result = JSON.parse(
            pako.inflate(reader.result, {
              to: "string"
            })
          );
          // console.log(result);

          if (result.ch == "market.btcusdt.detail") {
            _that.coinListHuobi[0].newprice = result.tick.close.toFixed(3);
            _that.coinListHuobi[0].newprice1 = (
              result.tick.close * _that.usdtCny
            ).toFixed(3);
            _that.coinListHuobi[0].ratio = (
              ((result.tick.close - result.tick.open) / result.tick.close) *
              100
            ).toFixed(2);
            _that.coinListHuobi[0].vol = result.tick.vol;
          }
          if (result.ch == "market.ethusdt.detail") {
            _that.coinListHuobi[1].newprice = result.tick.close.toFixed(3);
            _that.coinListHuobi[1].newprice1 = (
              result.tick.close * _that.usdtCny
            ).toFixed(3);
            _that.coinListHuobi[1].ratio = (
              ((result.tick.close - result.tick.open) / result.tick.close) *
              100
            ).toFixed(2);
            _that.coinListHuobi[1].vol = result.tick.vol;
          }
          if (result.ch == "market.eosusdt.detail") {
            _that.coinListHuobi[2].newprice = result.tick.close.toFixed(3);
            _that.coinListHuobi[2].newprice1 = (
              result.tick.close * _that.usdtCny
            ).toFixed(3);
            _that.coinListHuobi[2].ratio = (
              ((result.tick.close - result.tick.open) / result.tick.close) *
              100
            ).toFixed(2);
            _that.coinListHuobi[2].vol = result.tick.vol;
          }

          //pako.inflate()对数据进行解压，得到正常的json对象
          if (result.ping) {
            _that.websocketsend(
              JSON.stringify({
                pong: result.ping
              })
            );
            //响应服务器，避免断开连接
          }
        };
        reader.readAsBinaryString(evt.data);
        //将返回的数据解析为字符串格式
      }
    },
    websocketsend(Data) {
      //数据发送
      this.websock.send(Data);
    },
    websocketclose(e) {
      //关闭
      console.log("断开连接", e);
    },
    tab(index) {
      this.active = index;
      if (index > 0) {
        this.huobiGet24HTrade(index);
      }
      if (index > 0) {
        Toast("敬请期待");
      }
    },
    // 火币 其他币
    huobiGet24HTrade(index) {
      let symbol = "btcusdt";
      if (index == 1) {
        symbol = "btcusdt";
      } else if (index == 2) {
        symbol = "ethusdt";
      } else if (index == 3) {
        symbol = "eosusdt";
      }
      Services.huobiGet24HTrade({
        symbol: symbol
      }).then(res => {
        console.log(res);
        this.data = res.data;
        this.ratio2 = (
          ((res.data.close - res.data.open) / res.data.open) *
          100
        ).toFixed(2);
      });
    },
    // 最新成交价 vc
    getnewPrice() {
      Services.newPrice().then(res => {
        console.log(res);
        if (res.code == "0000") {
          this.newprice = res.vcPrice.toFixed(3);
          this.ratio = res.percent;
          this.volumn = res.kline.volumn;
        }
      });
    },
    // 下拉刷新 deling 00
    onRefresh(done) {
      setTimeout(() => {
        done();
        Toast(this.$t("m.refresh"));
      }, 2000);
    },
    onInfinite(done) {
      setTimeout(() => {
        done(0);
      });
    },
    goQuotionInfo(id) {
      // this.$router.push(`/quotationInfo?coin=${id}`);
      let coin = "vc_cnn";
      if (id == 0) {
        coin = "vc_cnn";
        //  t  1 买入  2 卖出
        this.$router.push(`/quotationTrade?s=${coin}&t=1`);
        return;
      } else if (id == 1) {
        coin = "btc_cnn";
      } else if (id == 2) {
        coin = "eth_cnn";
      } else if (id == 3) {
        coin = "eos_cnn";
      }
      //  t  1 买入  2 卖出
      this.$router.push(`/quotationTradeHuobi?s=${coin}&t=1`);
    }
  },
  destroyed() {
    // this.websock.close(); //离开路由之后断开websocket连接
    clearInterval(this.timer);
  }
};
</script>
<style lang="scss" scoped type="text/scss">
#quotation {
  height: 100%;
  .nav {
    padding: 0 0.3rem;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 0.88rem;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    background: #fff;
    box-shadow: 0 0.05rem 0.1rem rgba(0, 0, 0, 0.07);
    z-index: 999;
    span {
      display: flex;
      justify-content: center;
      align-items: center;
      color: #a8a7ab;
      font-size: 0.3rem;
      width: 25%;
      height: 100%;
      letter-spacing: 0.02rem;
      padding: 0 0.1rem;
      position: relative;
      &.active {
        font-size: 0.3rem;
        font-weight: bold;
        color: #40404c;
        &::after {
          content: "";
          display: block;
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 1rem;
          height: 0.05rem;
          background: #e4b577;
        }
      }
    }
  }
  .rootMain {
    height: calc(100% - 1.88rem);
    top: 0.88rem;
    overflow: hidden;
    .list {
      padding: 0.35rem;
      .list-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-bottom: 1px solid #f7f7fb;
        height: 1.1rem;
        > div {
          &.left {
            width: 30%;
          }
          &.center {
            flex: 1;
            padding: 0 0.4rem;
          }
          h4 {
            height: 0.5rem;
            display: flex;
            align-items: center;
            color: #1f3f59;
            font-size: 0.3rem;
            font-weight: 600;
            label {
              font-size: 0.22rem;
              color: #aaa;
              font-weight: normal;
            }
          }
          p {
            font-size: 0.22rem;
            color: #383838;
          }
          &.right {
            width: 1.5rem;
            .btn {
              margin: 0;
              width: 1.5rem;
              height: 0.75rem;
              line-height: 0.75rem;
              font-size: 0.22rem;
              border-radius: 0;
            }
          }
        }
      }
    }
  }
}
</style>